package com.qing.administer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.qing.administer.entity.SysUserRole;
import com.qing.administer.mapper.SysUserRoleMapper;
import com.qing.administer.service.SysUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户与角色对应关系 服务实现类
 * </p>
 *
 * @author qing
 * @since 2021-09-17
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {


    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean editSysUserRole(Long userId, List<Long> roleIds) {
        QueryWrapper<SysUserRole> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
       List<SysUserRole> existSysUserRoleList=sysUserRoleMapper.selectList(queryWrapper);

       //求集合交集--不需要改变的数据
       List<Long> commonRoleList= existSysUserRoleList.stream().map(item->item.getRoleId())
               .filter(item->roleIds.contains(item))
               .collect(Collectors.toList());

        //数据库--与交集的差集需要删除的部分
        List<Long> removeIds=existSysUserRoleList.stream().filter(item->!commonRoleList.contains(item.getRoleId())).map(item->item.getId()).collect(Collectors.toList());

        //传值--与交集的差集需要添加的部分
        roleIds.stream().filter(item->!commonRoleList.contains(item)) //取差集
                .map(roleId->new SysUserRole(userId,roleId)).forEach(sysUserRole->{
            sysUserRoleMapper.insert(sysUserRole);
        });

        if(CollectionUtils.isNotEmpty(removeIds)){
            sysUserRoleMapper.deleteBatchIds(removeIds);
        }
        return  true;
    }
}
